document.addEventListener('DOMContentLoaded', async () => {
  const resultContainer = document.getElementById('result-container');
  const resultDiv = document.getElementById('result');
  const copyBtn = document.getElementById('copyBtn');
  const uploadDirInput = document.getElementById('uploadDir');
  
  try {
    const { lastPreviewUrl, lastUploadDir } = await chrome.storage.local.get(['lastPreviewUrl', 'lastUploadDir']);
    
    // 设置上次使用的目录
    if (lastUploadDir) {
      uploadDirInput.value = lastUploadDir;
    }
    
    if (lastPreviewUrl) {
      resultDiv.innerHTML = '上次预览链接：<br/>' +
        `<a href="${lastPreviewUrl}" target="_blank">${lastPreviewUrl}</a>`;
      resultContainer.style.display = 'block';
      copyBtn.style.display = 'block';
      
      // 添加复制功能
      copyBtn.onclick = createCopyHandler(lastPreviewUrl, copyBtn);
    }
  } catch (err) {
    console.error('Failed to load last preview URL:', err);
  }

  // 加载设置
  const { apiKey, serverUrl } = await chrome.storage.local.get(['apiKey', 'serverUrl']);
  if (apiKey) document.getElementById('apiKey').value = apiKey;
  if (serverUrl) document.getElementById('serverUrl').value = serverUrl;
  
  // 如果没有配置，显示设置面板
  if (!apiKey || !serverUrl) {
    document.querySelector('.container:not(#settings-panel)').style.display = 'none';
    document.getElementById('settings-panel').style.display = 'block';
  }

  // 在popup页面加载时检查上传状态
  try {
    const response = await chrome.runtime.sendMessage({ type: 'checkUploadStatus' });
    if (response.isUploading) {
      // 如果正在上传，显示提示
      document.getElementById('uploadBtn').disabled = false;
      const resultDiv = document.getElementById('result');
      resultDiv.textContent = '检测到上次上传可能未完成。由于插件页面关闭会导致上传中断，请重新上传。';
      document.getElementById('result-container').style.display = 'block';
      document.getElementById('copyBtn').style.display = 'none';
      
      // 如果有上次的预览链接，保留显示
      const lastPreviewLink = resultDiv.querySelector('a');
      if (lastPreviewLink) {
        resultDiv.innerHTML += '<br/><br/>上次预览链接：<br/>' + lastPreviewLink.outerHTML;
        document.getElementById('copyBtn').style.display = 'block';
      }
      
      // 重置上传状态
      chrome.runtime.sendMessage({ type: 'uploadFinished' });
    }
  } catch (err) {
    console.error('Failed to check upload status:', err);
  }
});

document.getElementById('uploadBtn').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  // 清除之前的提示信息
  const resultContainer = document.getElementById('result-container');
  const resultDiv = document.getElementById('result');
  const copyBtn = document.getElementById('copyBtn');
  resultContainer.style.display = 'none';
  resultDiv.textContent = '';
  copyBtn.style.display = 'none';
  
  // 检查URL是否为本地预览
  if (!/^http:\/\/127\.0\.0\.1:\d+\//.test(tab.url)) {
    resultDiv.textContent = '仅支持Axure本地预览页面上传';
    resultContainer.style.display = 'block';
    copyBtn.style.display = 'none';
    
    // 清除上次的预览链接
    try {
      await chrome.storage.local.remove(['lastPreviewUrl']);
    } catch (err) {
      console.error('Failed to clear last preview URL:', err);
    }
    return;
  }

  const uploadBtn = document.getElementById('uploadBtn');
  const progressContainer = document.getElementById('progress-container');
  const progress = document.getElementById('progress');
  const progressText = document.getElementById('progress-text');

  // 立即禁用上传按钮并显示进度
  uploadBtn.disabled = true;
  progressContainer.style.display = 'block';
  progress.style.width = '0%';
  progressText.textContent = '正在获取页面资源... 0%';
  
  try {
    // 显示资源获取进度
    progressText.textContent = '正在获取页面资源...';
    progress.style.width = '5%';

    const [{ result }] = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: getAxureContent
    });
    
    // 更新进度显示
    progress.style.width = '15%';
    progressText.textContent = '资源获取完成，准备上传...';
    
    // 在popup中进行上传
    await uploadContent(result);
    
  } catch (err) {
    resultDiv.textContent = '上传失败：' + err.message;
    resultContainer.style.display = 'block';
    // 重置进度条和按钮状态
    progressContainer.style.display = 'none';
    uploadBtn.disabled = false;
    progress.style.width = '0%';
  }
});

// 获取Axure预览内容
function getAxureContent() {
  const resources = [];
  const baseUrl = document.baseURI;
  
  // 获取当前页面的路径部分
  const currentPath = new URL(baseUrl).pathname;
  const basePath = currentPath.substring(0, currentPath.lastIndexOf('/') + 1);
  
  // 获取所有脚本文件
  document.querySelectorAll('script').forEach(script => {
    if (script.src) {
      const url = new URL(script.src);
      resources.push({
        url: script.src,
        path: url.pathname.replace(basePath, '')
      });
    }
  });
  
  // 获取所有样式文件
  document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
    if (link.href) {
      const url = new URL(link.href);
      resources.push({
        url: link.href,
        path: url.pathname.replace(basePath, '')
      });
    }
  });
  
  // 获取所有图片
  document.querySelectorAll('img').forEach(img => {
    if (img.src) {
      const url = new URL(img.src);
      resources.push({
        url: img.src,
        path: url.pathname.replace(basePath, '')
      });
    }
  });
  
  // 获取主文件名
  let mainFileName = '原型设计.html';
  document.querySelectorAll('script').forEach(script => {
    const content = script.textContent;
    if (content && content.includes('$axure.loadDocument(')) {
      const match = content.match(/\$axure\.loadDocument\('(.+?)'\)/);
      if (match) {
        mainFileName = match[1];
        const url = new URL(mainFileName, baseUrl);
        resources.push({
          url: url.href,
          path: mainFileName,
          isMainFile: true,
          isMainPage: true
        });
      }
    }
  });

  // 获取Axure特定的资源文件（按确的加载顺序排列）
  const axureFiles = [
    // 基础库最先加载）
    'resources/scripts/jquery-1.7.1.min.js',
    'resources/scripts/jquery-ui-1.8.10.custom.min.js',
    'resources/scripts/prototypePre.js',
    
    // Axure核心文件
    'resources/scripts/axure/axQuery.js',
    'resources/scripts/axure/globals.js',
    'resources/scripts/axure/utils.temp.js',
    'resources/scripts/axure/annotation.js',
    'resources/scripts/axure/axQuery.std.js',
    'resources/scripts/axure/doc.js',
    'resources/scripts/messagecenter.js',
    
    // 数据文件（在核心文件之后加载）
    'data/document.js',
    'files/data.js',
    'files/page/data.js',
    
    // 其他功能文件
    'resources/scripts/axure/events.js',
    'resources/scripts/axure/recording.js',
    'resources/scripts/axure/geometry.js',
    'resources/scripts/axure/flyout.js',
    'resources/scripts/axure/legacy.js',
    'resources/scripts/axure/viewer.js',
    'resources/scripts/axure/math.js',
    'resources/scripts/axure/jquery.nicescroll.min.js',
    'resources/scripts/axure/model.js',
    'resources/scripts/axure/repeater.js',
    'resources/scripts/axure/sto.js',
    'resources/scripts/axure/adaptive.js',
    'resources/scripts/axure/tree.js',
    'resources/scripts/axure/init.js',

    'resources/scripts/axure/action.js',
    'resources/scripts/axure/drag.js',
    'resources/scripts/axure/expr.js',
    'resources/scripts/axure/ie.js',
    'resources/scripts/axure/init.temp.js',
    'resources/scripts/axure/ios.js',
    'resources/scripts/axure/move.js',
    'resources/scripts/axure/style.js',
    'resources/scripts/axure/variables.js',
    'resources/scripts/axure/visibility.js',
    'resources/scripts/player/splitter.js',
    
    // CSS文件
    'resources/css/axure_rp_page.css',
    'data/styles.css',
    'files/page/styles.css',
    
    'resources/css/jquery-ui-themes.css',
    'resources/css/previewfonts.css',

    
    // 插件文件（最后加载）
    'plugins/sitemap/styles/sitemap.css',
    'plugins/page_notes/styles/page_notes.css',
    'plugins/debug/styles/debug.css',
    'plugins/sitemap/sitemap.js',
    'plugins/page_notes/page_notes.js',
    'plugins/debug/debug.js',
    'plugins/recordplay/styles/recordplay.css',
    'plugins/recordplay/recordplay.js',
  ];

  // 添加图片资源
  const imageFiles = [
    'resources/images/close.svg',
    'resources/images/axure9_logo.svg',
    'resources/images/overflow-icon.svg',
    'resources/images/caret_down.svg',
    'resources/images/left_arrow.svg',
    'plugins/sitemap/styles/images/sitemap_panel_on.svg',
    'plugins/page_notes/styles/images/notes_panel_off.svg',
    'plugins/page_notes/styles/images/notes_panel_on.svg',
    'plugins/debug/styles/images/console_panel_off.svg',
    'plugins/debug/styles/images/console_panel_on.svg',

    'plugins/sitemap/styles/images/back_keys.svg',
    'plugins/sitemap/styles/images/closed_item.svg',
    'plugins/sitemap/styles/images/flow.svg',
    'plugins/sitemap/styles/images/folder_closed_blue.svg',
    'plugins/sitemap/styles/images/forward_keys.svg',
    'plugins/sitemap/styles/images/left_arrow.svg',
    'plugins/sitemap/styles/images/open_item.svg',
    'plugins/sitemap/styles/images/page_lt_grey.svg',
    'plugins/sitemap/styles/images/right_arrow.svg',
    'plugins/sitemap/styles/images/search_off.svg',
    'plugins/sitemap/styles/images/search_on.svg',
    'plugins/sitemap/styles/images/sitemap_panel_off.svg',
    
    'resources/css/images/images.html',
    'resources/css/images/newwindow.gif',
    'resources/css/images/note.gif',
    'resources/css/images/touch.cur',
    'resources/css/images/touch.svg',
    'resources/css/images/ui-bg_flat_0_aaaaaa_40x100.png',
    'resources/css/images/ui-bg_glass_55_fbf9ee_1x400.png',
    'resources/css/images/ui-bg_glass_65_ffffff_1x400.png',
    'resources/css/images/ui-bg_glass_75_dadada_1x400.png',
    'resources/css/images/ui-bg_glass_75_e6e6e6_1x400.png',
    'resources/css/images/ui-bg_glass_75_ffffff_1x400.png',
    'resources/css/images/ui-bg_highlight-soft_75_cccccc_1x100.png',
    'resources/css/images/ui-bg_inset-soft_95_fef1ec_1x100.png',
    'resources/css/images/ui-icons_2e83ff_256x240.png',
    'resources/css/images/ui-icons_222222_256x240.png',
    'resources/css/images/ui-icons_454545_256x240.png',
    'resources/css/images/ui-icons_888888_256x240.png',
    'resources/css/images/ui-icons_cd0a0a_256x240.png',
    'resources/css/previewfonts/SourceSansPro-OpenFontLicense.txt',
    'resources/css/previewfonts/SourceSansPro-Regular.woff2',
    'resources/css/previewfonts/SourceSansPro-Semibold.woff2',
  ];

  // 获取文件内容
  function file_get_contents(filename) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', filename, false);
    xhr.send();
    return xhr.responseText;
  }

  var myNodelist = document.querySelectorAll('a');
  for (var i = 0; i < myNodelist.length; i++) {
    var nodeurl = myNodelist[i].getAttribute('nodeurl')
    if (nodeurl) {
      axureFiles.push(nodeurl)

      let htmlContent = file_get_contents(nodeurl)
      let dom = new DOMParser().parseFromString(htmlContent, "text/html");
      dom.querySelectorAll('img').forEach(img => {
        if (img.src) {
          const url = new URL(img.src)
          axureFiles.push(decodeURI(url.pathname.replace(basePath, '')))
        }
      })

      let path = nodeurl.replace(/\.html$/, '')
      axureFiles.push('files/' + path + '/' + 'data.js')
      axureFiles.push('files/' + path + '/' + 'styles.css')
    }
  }

  axureFiles.push(...[
    'start_with_pages.html',
    'start_c_1.html',
    'start.html',
    // 'index.html',
  ])

  // 合并所有资源
  axureFiles.push(...imageFiles);

  axureFiles.forEach(file => {
    const url = new URL(file, baseUrl);
    resources.push({
      url: url.href,
      path: file
    });
  });

  // 修改HTML内容
  let modifiedHtml = document.documentElement.outerHTML;
  
  // 替换资源路径
  resources.forEach(resource => {
    const originalUrl = resource.url;
    const newPath = resource.path.replace(/^\/+/, '');
    modifiedHtml = modifiedHtml.replace(
      new RegExp(originalUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'),
      newPath
    );
  });
  
  // 修复双斜杠问题
  modifiedHtml = modifiedHtml.replace(/(['"]\/)\/+/g, '$1');

  return {
    html: modifiedHtml,
    url: window.location.href,
    resources: [...new Set(resources.map(JSON.stringify))].map(JSON.parse),
    baseUrl,
    mainFileName
  };
}

// 修改上传内容的函数
async function uploadContent(pageData) {
  const serverUrl = CONFIG.SERVER_URL;
  const resultContainer = document.getElementById('result-container');
  const resultDiv = document.getElementById('result');
  const copyBtn = document.getElementById('copyBtn');
  const uploadBtn = document.getElementById('uploadBtn');
  const progressContainer = document.getElementById('progress-container');
  const progress = document.getElementById('progress');
  const progressText = document.getElementById('progress-text');
  const uploadDir = document.getElementById('uploadDir').value.trim();
  let previewUrl = '';
  
  if (!uploadDir) {
    resultDiv.textContent = '请输入上传目录';
    resultContainer.style.display = 'block';
    progressContainer.style.display = 'none';
    uploadBtn.disabled = false;
    return;
  }
  
  // 计算总资源
  const totalResources = pageData.resources.length;
  let loadedResources = 0;
  
  try {
    // 通知background script开始上传
    await chrome.runtime.sendMessage({ type: 'uploadStarted' });
    
    // 添加关闭提示
    progressText.textContent = '正在上传... (关闭插件页面会终止上传)';
    
    // 将资源分块处理，每块最多50个资源
    const chunkSize = 50;
    const chunks = [];
    for (let i = 0; i < pageData.resources.length; i += chunkSize) {
      chunks.push(pageData.resources.slice(i, i + chunkSize));
    }
    
    let processedResources = [];
    // 资源处理进度范围：15%-40%
    for (let i = 0; i < chunks.length; i++) {
      const chunk = chunks[i];
      const resourceContents = await Promise.all(
        chunk.map(async resource => {
          try {
            const response = await fetch(resource.url, {
              headers: {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
              }
            });
            
            const contentType = response.headers.get('content-type');
            const isImage = contentType && contentType.includes('image');
            const content = await (isImage ? response.blob() : response.text());
            
            // 更新进度
            loadedResources++;
            const percentage = 15 + Math.round((loadedResources / totalResources) * 25);
            progress.style.width = percentage + '%';
            progressText.textContent = `正在处理资源... ${Math.round((loadedResources / totalResources) * 100)}%`;
            
            return {
              url: resource.url,
              path: resource.path,
              content: isImage ? await blobToBase64(content) : content,
              isBase64: isImage
            };
          } catch (error) {
            console.error('Failed to fetch resource:', resource.url, error);
            return null;
          }
        })
      );
      processedResources = [...processedResources, ...resourceContents];
    }

    // 准备上传数据
    progress.style.width = '40%';
    progressText.textContent = '准备上传数据...';

    // 模拟上传进度
    let uploadProgress = 40;
    const progressInterval = setInterval(() => {
      if (uploadProgress < 90) {
        uploadProgress += Math.random() * 2;
        progress.style.width = uploadProgress + '%';
        progressText.textContent = '正在上传到服务器...';
      }
    }, 200);

    // 将数据分成小块上传
    const jsonData = JSON.stringify({
      html: pageData.html,
      url: pageData.url,
      resources: processedResources.filter(r => r !== null),
      baseUrl: pageData.baseUrl,
      uploadDir: uploadDir,
      checksum: await generateChecksum(pageData.html, uploadDir)
    });

    const response = await fetch(serverUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': CONFIG.API_KEY,
        'X-Request-Timestamp': new Date().toISOString()
      },
      credentials: 'omit',
      body: jsonData
    });
    
    // 清除模拟进度定时器
    clearInterval(progressInterval);
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    // 根据服务器返回的保存进度更新显示
    if (data.progress) {
      const { current, total } = data.progress;
      const savePercentage = 90 + Math.round((current / total) * 10);
      progress.style.width = savePercentage + '%';
      progressText.textContent = `正在保存文件... ${Math.round((current / total) * 100)}%`;
    }
    
    if (!data.success) {
      throw new Error(data.error || '上传失败');
    }
    
    previewUrl = data.previewUrl;
    // 保存预览链接到storage
    try {
      await chrome.storage.local.set({ 
        lastPreviewUrl: previewUrl,
        lastUploadDir: uploadDir
      });
    } catch (err) {
      console.error('Failed to save settings:', err);
    }
    
    resultDiv.innerHTML = '上传成功！预览链接：<br/>' +
      `<a href="${previewUrl}" target="_blank">${previewUrl}</a>`;
    resultContainer.style.display = 'block';
    copyBtn.style.display = 'block';
    
    // 使用提取的复制功能
    copyBtn.onclick = createCopyHandler(previewUrl, copyBtn);

    // 完成时显示100%
    progress.style.width = '100%';
    progressText.textContent = '上传完成！';
    
    // 短暂延迟后隐藏进度条
    setTimeout(() => {
      progressContainer.style.display = 'none';
      uploadBtn.disabled = false;
      // 通知background script上传完成
      chrome.runtime.sendMessage({ type: 'uploadFinished' });
    }, 1000);  // 延长显示时间

  } catch (error) {
    console.error('Upload error:', error);
    resultDiv.textContent = '上传失败：' + error.message;
    resultContainer.style.display = 'block';
    copyBtn.style.display = 'none';
    // 通知background script上传失败
    chrome.runtime.sendMessage({ type: 'uploadFinished' });
  } finally {
    // 隐藏进度条，重置上传按钮
    progressContainer.style.display = 'none';
    uploadBtn.disabled = false;
    progress.style.width = '0%';
    progressText.textContent = '正在上传... 0%';
    // 确保在任何情况下都通知background script上传结束
    chrome.runtime.sendMessage({ type: 'uploadFinished' });
  }
}

// 辅助函数：将Blob转换为Base64
function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

// 提取复制功能为独立函数
function createCopyHandler(textToCopy, button) {
  return async () => {
    try {
      await navigator.clipboard.writeText(textToCopy);
      const originalText = button.textContent;
      button.textContent = '已复制！';
      setTimeout(() => {
        button.textContent = originalText;
      }, 1500);
    } catch (err) {
      console.error('复制失败:', err);
      const resultDiv = document.getElementById('result');
      resultDiv.textContent += '\n复制失败：' + err.message;
    }
  };
}

// 生成验和
async function generateChecksum(content, uploadDir) {
  const data = content + uploadDir + CONFIG.API_KEY;
  const msgBuffer = new TextEncoder().encode(data);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// 设置按钮点击事件
document.getElementById('settingsBtn').addEventListener('click', () => {
  document.querySelector('.container:not(#settings-panel)').style.display = 'none';
  document.getElementById('settings-panel').style.display = 'block';
});

// 返回按钮点击事件
document.getElementById('backBtn').addEventListener('click', () => {
  document.querySelector('.container:not(#settings-panel)').style.display = 'block';
  document.getElementById('settings-panel').style.display = 'none';
});

// 保存设置按钮点击事件
document.getElementById('saveSettingsBtn').addEventListener('click', async () => {
  const apiKey = document.getElementById('apiKey').value.trim();
  const serverUrl = document.getElementById('serverUrl').value.trim();
  
  if (!apiKey || !serverUrl) {
    alert('请填写所有必填项');
    return;
  }
  
  try {
    await chrome.storage.local.set({ apiKey, serverUrl });
    CONFIG.API_KEY = apiKey;
    CONFIG.SERVER_URL = serverUrl;
    document.querySelector('.container:not(#settings-panel)').style.display = 'block';
    document.getElementById('settings-panel').style.display = 'none';
  } catch (err) {
    console.error('Failed to save settings:', err);
    alert('保存设置失败');
  }
});

// 添加unload事件监听器
window.addEventListener('unload', () => {
  if (isUploading) {
    // 可以在这里添加取消上传的逻辑
    console.log('插件被强制关闭，上传可能未完成');
  }
}); 